<template>
  <div>
    <!-- 1.顶部栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 2.搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      autofocus
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 3.搜索列表 -->
    <van-cell-group>
      <van-cell v-for="(item, index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:SuggestionList[index]}})"
      >
        <template #title>
          <div class="custom-title" v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "", //搜索内容
      SuggestionList: [],
    };
  },
  methods: {
    /* 搜索事件：输入框回车+点击右侧搜索按钮 */
    onSearch() {
      console.log("搜索" + this.value);
      //跳转搜索结果页并传参
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    /* 输入事件：输入框内容变化 */
     onInput() {
      /* 防抖第一步，先清除上一次定时器，以最后一次为准 */
      clearTimeout(this.timeID)
      /* 防抖第二步：开启防抖定时器 */
      this.timeID=setTimeout(async ()=>{
        console.log("输入" + this.value);
        //非空判断
      if (this.value == "") {
        this.suggestionList = [];
        return;
      }
      //1.获取推荐词列表
      let res = await getSuggestion(this.value);
      console.log(res);
      //2.绑定数据
      this.SuggestionList = res.data.data.options;
      },500)
      
      
    },
  },
  computed: {
    showList() {
      //map:遍历数组，根据某种映射规生成一个新数组
      //这个return返回计算属性值
      return this.SuggestionList.map((value) => {
        let reg = new RegExp(this.value, "ig");
        //这个return返回映射新数组
        return (reg = value.replace(
          reg,
          (match) => `<span style="color:red">${match}</span>`
        ));
      });
    },
  },
};
</script>

<style>
</style>